import json
from orders.models import OrdersModel
from orders.serializers import OrderModelSerializer
from rest_framework.generics import RetrieveAPIView
from rest_framework.views import APIView
from doctors.models import DoctorModel, EvaluateModel, AnswerModel, AnswerImageModel
from rest_framework.response import Response
from rest_framework import status
from doctors.serializers import DoctorModelSerializer, AnswerModelSerializer, AnswerImageModelSerializer
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection


class DoctorAPIView(APIView):
    def get(self, request, id):
        doctor_list = DoctorModel.objects.filter(department_id=id)
        doctor_id_list = [item.id for item in doctor_list]
        evaluate_list = EvaluateModel.objects.filter(doctor_id__in=doctor_id_list).order_by('-star')[:4]
        evaluate_doctor_id_list = [item.doctor_id for item in evaluate_list]
        data = []
        sort = 1
        for i in evaluate_doctor_id_list:
            doctor_info = DoctorModel.objects.filter(id=i).first()
            evaluate_star_list = EvaluateModel.objects.filter(doctor_id=i)
            star_all = [float(item.star) for item in evaluate_star_list]
            # 查询医生每月的回答量  待开发
            answer_list = AnswerModel.objects.filter(doctor_id=i)
            answer = 0
            if len(answer_list) > 0:
                answer = len(answer_list)
            else:
                answer = 0
            star = sum(star_all) / len(star_all)
            doctor_info_dict = {
                'id': doctor_info.id,
                'sort': sort,
                'avatar': "http://127.0.0.1:8000/uploads/" + str(doctor_info.avatar),
                'name': str(doctor_info.name),
                'title': str(doctor_info.get_title_display()),
                'hospital': str(doctor_info.hospital),
                'department': str(doctor_info.department),
                'star': f'{star:.2f}',
                'answer': answer,
                'profile': str(doctor_info.profile),
                'price': str(doctor_info.price),
            }
            sort += 1
            data.append(doctor_info_dict)

        return Response({'message': '医生信息列表查询成功！', 'data': data}, status=status.HTTP_200_OK)


# 医生信息视图
class DoctorRetrieveAPIView(RetrieveAPIView):
    queryset = DoctorModel.objects.all()
    serializer_class = DoctorModelSerializer



class DoctorInfoAPIView(APIView):
    def get(self, request, id):
        # 查询医生的评价星星等级
        evaluate_list = EvaluateModel.objects.filter(doctor_id=id)
        star_all = [float(item.star) for item in evaluate_list]
        data = {}
        if len(star_all) > 0:
            star = sum(star_all) / len(star_all)
            data['star'] = f'{star:.2f}'
        else:
            data['star'] = 0
        # 查询医生每月的回答量  待开发
        answer_list = AnswerModel.objects.filter(doctor_id=id)
        if len(answer_list) > 0:
            data['answer'] = len(answer_list)
        else:
            data['answer'] = 0

        return Response({'message': '医生评价和月回答量查询成功', 'data': data}, status=status.HTTP_200_OK)


class DoctorIllnessAPIView(APIView):
    def get(self, request, id):
        answer_list = AnswerModel.objects.filter(doctor_id=id)
        return Response({'message': '医生回答列表查询成功！', 'data': {'answer_length':len(answer_list)}}, status=status.HTTP_200_OK)


# class AnswerAPIView(APIView):
#     permission_classes = [IsAuthenticated, ]
#
#     def post(self, request):
#         user_id = request.user.id
#         doctor_id = request.data.get('doctor')
#         redis = get_redis_connection("answer")
#         answer_info = redis.hgetall(f'{user_id}:{doctor_id}:1')
#         if answer_info:
#             is_commit = redis.hget(f'{user_id}:{doctor_id}:1', 'is_commit').decode()
#             if is_commit == '0':
#                 answer_id = redis.hget(f'{user_id}:{doctor_id}:1', 'answer_id').decode()
#                 answer = AnswerModel.objects.filter(id=answer_id).first()
#                 answer_ser = AnswerModelSerializer(instance=answer)
#                 redis_image_list = redis.hget(f'{user_id}:{doctor_id}:1', 'image_list').decode()
#                 image_id_list = [int(i['image']) for i in json.loads(redis_image_list)]
#                 image_list = AnswerImageModel.objects.filter(id__in=image_id_list)
#                 image_data = []
#                 for i in image_list:
#                     with open(i.image.path, 'rb', encoding='utf-8') as f:
#                         content = f.read()
#                     image_data.append(content)
#                 data = []
#                 data.append(
#                     {
#                      'answer': answer_ser.data,
#                      # 'image_list': image_ser.data
#                      # 'image_list': json.dumps(image_data)
#                     }
#                 )
#                 return Response({'message': '问题查询成功！', 'data': data, 'image': image_data}, status=status.HTTP_200_OK, content_type='image/jpeg')
#             else:
#                 return Response({'message': '问题已经被提交，不能重复获取'}, status=status.HTTP_200_OK)
#         else:
#             return Response({'message': '没有未提交过任何问题'}, status=status.HTTP_200_OK)


class AnswerAPIView(APIView):
    permission_classes = [IsAuthenticated, ]

    def post(self, request):
        answer_id = request.data.get('answer_id')
        doctor_id = request.data.get('doctor_id')
        order_id = request.data.get('order_id')
        answer_info = AnswerModel.objects.filter(id=answer_id).first()
        answer_ser = AnswerModelSerializer(instance=answer_info)
        doctor_info = DoctorModel.objects.filter(id=doctor_id).first()
        doctor_ser = DoctorModelSerializer(instance=doctor_info)
        order_info = OrdersModel.objects.filter(id=order_id).first()
        orders_ser = OrderModelSerializer(instance=order_info)
        data = {
            "answer_info": answer_ser.data,
            "doctor_info": doctor_ser.data,
            "order_info": orders_ser.data
        }
        return Response({'message': '问题查询成功！', 'data': data}, status=status.HTTP_200_OK)


class DoctorListAPIView(APIView):
    def get(self, request, id):
        doctor_list = DoctorModel.objects.filter(department_id=id)
        doctor_id_list = [item.id for item in doctor_list]
        evaluate_list = EvaluateModel.objects.filter(doctor_id__in=doctor_id_list).order_by('-star')
        evaluate_doctor_id_list = [item.doctor_id for item in evaluate_list]
        data = []
        sort = 1
        for i in evaluate_doctor_id_list:
            doctor_info = DoctorModel.objects.filter(id=i).first()
            evaluate_star_list = EvaluateModel.objects.filter(doctor_id=i)
            star_all = [float(item.star) for item in evaluate_star_list]
            # 查询医生每月的回答量  待开发
            answer_list = AnswerModel.objects.filter(doctor_id=i)
            answer = 0
            if len(answer_list) > 0:
                answer = len(answer_list)
            else:
                answer = 0
            star = sum(star_all) / len(star_all)
            doctor_info_dict = {
                'id': doctor_info.id,
                'sort': sort,
                'avatar': "http://127.0.0.1:8000/uploads/" + str(doctor_info.avatar),
                'name': str(doctor_info.name),
                'title': str(doctor_info.get_title_display()),
                'hospital': str(doctor_info.hospital),
                'department': str(doctor_info.department),
                'star': f'{star:.2f}',
                'answer': answer,
                'profile': str(doctor_info.profile),
                'price': str(doctor_info.price),
                'level': str(doctor_info.hospital.get_level_display())
            }
            sort += 1
            data.append(doctor_info_dict)

        return Response({'message': '医生信息列表查询成功！', 'data': data}, status=status.HTTP_200_OK)
